﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RonYee.Models;
using System.Data.Linq.SqlClient;
using RonYee.Service;
using System.Data.Entity.Validation;

namespace RonYee.Controllers
{
    public class InStoreController : Controller
    {
        RongeDb db = new RongeDb();
        //
        // GET: /InStore/
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Index()
        {
            RonYee.Models.MvcPage Model = new MvcPage();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<InStore> datesource = GetDataSource();//要分页的数据源
            Model.InStoreList = datesource.Where(r => r.InStoreId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.InStoreList = datesource.Where(r => r.InStoreId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<InStore> GetDataSource()
        {
            var instore = from b in db.InStores
                          orderby b.BookName ascending
                          select b;
            List<InStore> model = new List<InStore>();
            foreach (var item in instore)
            {
                model.Add(item);
            }
            return model;
        }

        public ActionResult PageIndex(RonYee.Models.MvcPage Model)
        {

            //分页数据源。自己写逻辑获取。


            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<InStore> datesource = GetDataSource();//要分页的数据源
            Model.InStoreList = datesource.Where(r => r.InStoreId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("Index", Model);
            }
            //return View(Model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Search()
        {
            string isbn = Request.Form["s_isbn"];
            string name = Request.Form["s_name"];
            string area = Request.Form["s_area"];
            string hold = Request.Form["s_hold"];
            //1111
            if (isbn != "" && name != "" && area != "" && hold != "")
            {
                var book = from b in db.InStores
                       where b.ISBN.Contains(isbn) && b.BookName.Contains(name) && b.StorageArea1.Contains(area) && b.HoldUser.Contains(hold)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //1110
            else if (isbn != "" && name != "" && area != "" && hold == "")
            {
                var book = from b in db.InStores
                       where b.ISBN.Contains(isbn) && b.BookName.Contains(name) && b.StorageArea1.Contains(area)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //1101
            else if (isbn != "" && name != "" && area == "" && hold != "")
            {
                var book = from b in db.InStores
                       where b.ISBN.Contains(isbn) && b.BookName.Contains(name) && b.HoldUser.Contains(hold)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //1011
            else if (isbn != "" && name == "" && area != "" && hold != "")
            {
                var book = from b in db.InStores
                       where b.ISBN.Contains(isbn) && b.StorageArea1.Contains(area) && b.HoldUser.Contains(hold)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //0111
            else if (isbn == "" && name != "" && area != "" && hold != "")
            {
                var book = from b in db.InStores
                       where b.ISBN.Contains(isbn) && b.StorageArea1.Contains(area) && b.HoldUser.Contains(hold)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //0011
            else if (isbn == "" && name == "" && area != "" && hold != "")
            {
                var book = from b in db.InStores
                       where b.StorageArea1.Contains(area) && b.HoldUser.Contains(hold)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //1100
            else if (isbn != "" && name != "" && area == "" && hold == "")
            {
                var book = from b in db.InStores
                       where b.ISBN.Contains(isbn) && b.BookName.Contains(name)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //1010
            else if (isbn != "" && name == "" && area != "" && hold == "")
            {
                var book = from b in db.InStores
                           where b.ISBN.Contains(isbn) && b.StorageArea1.Contains(area)
                           orderby b.ISBN ascending
                           select b;
                return View(book);
            }
            //0101
            else if (isbn == "" && name != "" && area == "" && hold != "")
            {
                var book = from b in db.InStores
                       where b.BookName.Contains(name) && b.HoldUser.Contains(hold)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //0110
            else if (isbn == "" && name != "" && area != "" && hold == "")
            {
                var book = from b in db.InStores
                       where b.BookName.Contains(name) && b.StorageArea1.Contains(area)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //1001
            else if (isbn != "" && name == "" && area == "" && hold != "")
            {
                var book = from b in db.InStores
                       where b.ISBN.Contains(isbn) && b.HoldUser.Contains(hold)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //1000
            else if (isbn != "" && name == "" && area == "" && hold == "")
            {
                var book = from b in db.InStores
                       where b.ISBN.Contains(isbn)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //0100
            else if (isbn == "" && name != "" && area == "" && hold == "")
            {
                var book = from b in db.InStores
                       where b.BookName.Contains(name)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //0010
            else if (isbn == "" && name == "" && area != "" && hold == "")
            {
                var book = from b in db.InStores
                       where b.StorageArea1.Contains(area)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            //0001
            else if (isbn == "" && name == "" && area == "" && hold != "")
            {
                var book = from b in db.InStores
                       where b.HoldUser.Contains(hold)
                       orderby b.ISBN ascending
                       select b;
                return View(book);
            }
            else 
            {
                return RedirectToAction("Index");
            }
            
        }



        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Details(int id) 
        {
            InStore book = db.InStores.Find(id);

            return View(book);
        }

        #region  //对图书库存表InStores进行管理

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Create()
        {
            string isbn = Request.Form["s_isbn"];
            InStore model = new InStore();
            if (isbn != "") 
            {
                var instore = (from a in db.InStores
                               where a.ISBN == isbn
                               select a).FirstOrDefault();
                model = instore;
            }
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult AddBooksToStore()
        {
            string isbn = Request.Form["ISBN"];
            string bookName = Request.Form["BookName"];

            InStore instore = new InStore
            {
                ISBN = isbn,
                BookName = bookName,
                StorageArea1 = Request.Form["StorageArea1"],
                StorageArea2 = Request.Form["StorageArea1"],
                AddTime = DateTime.Now,
                HoldUser=Request.Form["holdUser"],
                Editor = HttpContext.User.Identity.Name
            };
            db.InStores.Add(instore);
            db.SaveChanges();

            //if(true)更改books表中的count;else 在books表创建新条目
            if (GetBooksInfo.HasBook(isbn))
            {
                UpdateInBooks(isbn);
                return RedirectToAction("Index");
            }
            else 
            {
                //Books表中没有该条目，返回一个model到books表的Create
                AddNewItemToBooks(isbn, bookName);
                int bookId = GetBooksInfo.GetBooksID(isbn);
                return RedirectToAction("Edit", "Book", new { id = bookId });
            }

        }

        #region  // 添加新的条目到Books表中【AddNewItemToBooks()】;在books表中修改Count数【UpdateInBooks()】
        //添加新的条目到Books表中
        public void AddNewItemToBooks(string isbn,string bookName) 
        {
            Book b = new Book
            {
                ISBN = isbn,
                BookName = bookName,
                Publisher = "Default Value",
                PublishNum = "Default Value",
                Author = "Default Value",
                BookCount = GetBooksInfo.GetBooksCount(isbn),
                OriginalPrice = 0,
                CurrentPrice = 0,
                BookImage = "~\\FilesPool\\BookCover\\DefaultCover.jpg",
                DelImgUrl = "Default Value",
                BookType1 = "Default Value"
            };
            db.Books.Add(b);
            db.SaveChanges();
            
        }

        //在books表中修改Count数
        public void UpdateInBooks(string isbn)
        {
            try
            {
                int count = GetBooksInfo.GetBooksCount(isbn);
                int id = GetBooksInfo.GetBooksID(isbn);
                var b = db.Books.Find(id);
                if (b != null)
                {
                    b.BookCount = count;
                    UpdateModel(b);
                    db.SaveChanges();
                }
            }
            catch (Exception ex) 
            {
                ViewData["Message"] = ex.Message;
            }

        }

        #endregion

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Edit(int id)
        {
            InStore book = db.InStores.Find(id);
            return View(book);
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Edit()
        {
            int id = Convert.ToInt32(Request.Form["InStoreId"]);
            try
            {
                var b = db.InStores.Find(id);
                b.BookName = Request.Form["BookName"];
                b.StorageArea1 = Request.Form["StorageArea1"];
                b.StorageArea2 = Request.Form["StorageArea2"];
                b.HoldUser = Request.Form["holdUser"];
                UpdateModel(b);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = id });
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "修改失败，请查看详细错误信息:" + e);
                return RedirectToAction("Edit", new { id = id });
            }
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Delete(int id)
        {
            InStore book = db.InStores.Find(id);
            return View(book);
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Delete(int id, FormCollection collection)
        {
            //根据ISBN在books中更新Count
            var isbn = (from b in db.InStores
                        where b.InStoreId == id
                        select b.ISBN).FirstOrDefault();


            InStore book = db.InStores.Find(id);
            db.InStores.Remove(book);
            db.SaveChanges();

            //修改删除后图书的库存数
            UpdateInBooks(isbn);

            return RedirectToAction("Index");
        }
        
        //期末库存管理
        public ActionResult ClearingTheBooks() 
        {
            var book = from b in db.Books select b;
            foreach (var item in book)
            {
                string isbn = item.ISBN;
                //核对并修改当前库存图书数量

                if (GetBooksInfo.HasBook(isbn))
                {
                    UpdateInBooks(isbn);
                }
                else
                {
                    AddNewItemToBooks(isbn, item.BookName);
                }
            }
            db.SaveChanges();
            return RedirectToAction("Index");
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult ConfirmInfo(string isbn)
        {
            var book = (from a in db.InStores
                        where a.ISBN == isbn
                        select a).FirstOrDefault();

            JsonResult json = new JsonResult
            {
                Data = new
                {
                    list = book
                }
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        #endregion

    }
}
